import React from "react";
import { PlusOutlined } from '@ant-design/icons';
import {Form, Input, Button, Select, Switch, Spin, Upload, InputNumber} from 'antd';
import API from '../../api/api';
import {config, url} from '../../util/config'
import PicturesWall from "./PicturesWall";
const request = {
    action: url.file_upload_url,
    headers: {
        'Accept': "application/json",
        'Authorization': localStorage.getItem("token")
    },
}

const { Option } = Select;

const layout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 16,
    },
};

const tailLayout = {
    wrapperCol: {
        offset: 8,
        span: 16,
    },
};

let imageUrl = null;

export default class LinkInsert extends React.Component {

    constructor(props) {
        super(props);
        this.state={
            status:'N',
            sortNum:null,
            hasUploaded : false,
            type:this.props.type,
            spinStatus:false,
        }
    }

    hasFlashed = false;

    result;

    formRef = React.createRef();

    verify=(values)=>{
        if(values.image_url==null){
            return false
        }else return true
    }

    handleChange=(info)=>{
        if(info.fileList.length==1){
            if(info.fileList[0].status=="done"){
                this.image_url = info.fileList[0].response.result[0].FILE_URL
                this.setState({
                    hasUploaded : true
                })
            }
        }else {
            this.setState({
                hasUploaded : false
            })
        }
    }

    onFinish = (values) => {
        if(values.link!=undefined && values.link!="" && values.link.match(/(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|\:|\&|-)+)/g)==null){
            alert("鏈接必須含有http://或者https://前綴")
            return;
        }
        if(values.sortNum==null ||values.sortNum==""){
            values.sortNum=undefined
        }
        values.image_url = this.image_url
        console.log(values)
        if(this.state.type=="slideshow" || this.state.type=="small"){
            if(values.link==undefined || values.link==""){
                values.link = `<img src=${values.image_url}>`
            }else {
                if(values.openNewTab==true) {
                    values.link = `<a target="_blank" href=${values.link} ><img src=${values.image_url}></a>`
                }else {
                    values.link = `<a href=${values.link} ><img src=${values.image_url}></a>`
                }
            }
            //类型是轮播
            values.type=this.state.type;
            //规则校验
            if(!this.verify(values)){
                alert("图片内容不可为空")
                return
            }
        }else if(this.state.type=="link"){
            if(values.openNewTab==true) {
                values.link = `<a target="_blank" href=${values.link} >${values.name}</a>`
            }else {
                values.link = `<a href=${values.link} >${values.name}</a>`
            }
            //类型是链接
            values.type="link"
            if((values.name ==undefined || values.name == "") || (values.link == undefined || values.link == "")){
                alert("别名必须绑定链接")
                return
            }
        }
        //发送新增请求，成功返回ok,反正error
        this.setState({spinStatus:true},()=>{
            setTimeout(()=>{
                this.result = API.insertLink(values);
                if(this.result=="ok"){
                    this.onReset()
                    if(!this.hasFlashed){
                        //只有返回成功后，才会置父组件的状态值为true，即Modal关闭后实现列表刷新
                        this.props.result(true)
                        //执行上一步后，再本组件也加一个标记，来标识已经重置了父组件的刷新状态值status
                        this.hasFlashed = true;
                        this.setState({hasUploaded:false})
                    }
                }
                this.setState({
                    hasUploaded:false,
                    spinStatus:false,
                    status:'N'
                })
            },1000)
        })
    };

    onReset = () => {
        this.setState({status:'N'})
        this.formRef.current.resetFields();
    };

    getImageUrl(url){
        this.image_url = url
    }

    onChange =(value)=> {
        if(typeof value == "number" && value>0){
            let tmpStatus = API.sortNumLink({
                sortNum:value,
                linkType:this.state.type
            })
            if(tmpStatus=='Y'){
                this.setState({status:'Y'})
                this.setState({sortNum:value})
            }else {
                this.setState({status:'N'})
            }
        }
        console.log('changed', value);
    }

    handleCheckTpl = (rule, value, wrappedCallback) =>　{
        console.log("rule：",rule)
        console.log("value:",value)
        console.log("callback:",wrappedCallback)
        if (value) {
            const { aware } = this.props;
            const { fileList } = aware;
            const newFileList=fileList.map(item => ({...item}));
            if (!newFileList) {
                wrappedCallback('请上传相关图片');
            } else {
                newFileList.length ? wrappedCallback() : wrappedCallback('请上传相关图片');
            }
        }
        wrappedCallback();    // callback方法必须要有，否则会报错
    };

    render() {
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (
            <Spin spinning={this.state.spinStatus} tip="正在添加......">
                <Form
                    layout={layout}
                    tailLayout={tailLayout}
                    ref={this.formRef}
                    name="control-ref"
                    onFinish={this.onFinish}
                    onReset={this.onReset}
                >
                    {this.state.type=="link" ?
                        <Form.Item
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                            name="name"
                            label="别名"
                        >
                            <Input ></Input>
                        </Form.Item>
                        :
                        <Form.Item
                            rules={[{required: true}]}
                            name="image_url"
                            label="图片"
                        >
                            <Upload
                                {...request}
                                listType="picture-card"
                                onPreview={this.handlePreview}
                                onChange={this.handleChange}
                                beforeUpload={this.beforeUpload}
                            >
                                {this.state.hasUploaded ? null : uploadButton}
                            </Upload>
                            {/*<PicturesWall render={this.getImageUrl}/>*/}
                        </Form.Item>

                        // <Form.Item
                        //     rules={[
                        //         {
                        //             required: true,
                        //             message: 'Please confirm your password!',
                        //         },
                        //         ({ getFieldValue }) => ({
                        //             validator(_, value) {
                        //                 console.log("validate:",value);
                        //                 if (!value || getFieldValue('image_url') === value) {
                        //                     return Promise.resolve();
                        //                 }
                        //                 return Promise.reject(new Error('The two passwords that you entered do not match!'));
                        //             },
                        //         }),
                        //     ]}
                        //     name="image_url"
                        //     label="图片"
                        // >
                        //     <PicturesWall render={this.getImageUrl}/>
                        // </Form.Item>
                    }

                    <Form.Item
                        rules={
                                [
                                    // ({ getFieldValue }) => ({
                                    //     validator(_, value) {
                                    //         let result;
                                    //         if(value!=undefined || value!=""){
                                    //             result = value.match(/(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|\:|\&|-)+)/g)
                                    //         }
                                    //         if (result!=null) {
                                    //             return Promise.resolve();
                                    //         }
                                    //         return Promise.reject(new Error("必须含有http://或https://前缀"));
                                    //     },
                                    // }),
                                    {
                                        required: this.state.type=="link" ? true : false,
                                    }
                                ]
                        }
                        name={"link"}
                        label={"链接"}
                    >
                        <Input ></Input>
                    </Form.Item>
                    <Form.Item label="排序" name="sortNum"  validateStatus={this.state.status=='Y'? "warning":null} help={this.state.status=='Y'?`序号冲突，提交会将该笔数据序号置为${this.state.sortNum}` : null }>
                        {/*<InputNumber min={1}/>*/}
                        <InputNumber min={1} onChange={this.onChange}/>
                    </Form.Item>
                    <Form.Item
                        name={"openNewTab"}
                        label={"开启新窗口"}
                    >
                        <Switch/>
                    </Form.Item>
                    <Form.Item
                        label="提交修改"
                        name="commit"
                    >
                        <Button type="primary" disabled={this.state.spinStatus} htmlType="submit">
                            提交
                        </Button>
                        <Button htmlType="reset" style={{marginLeft:"1rem"}}>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </Spin>
        );
    }
}













// import {Input, InputNumber, Modal} from "antd";
// import SelectRole from "./SelectRole";
// import React from "react";
//
// <span>用户工号</span>
// <Input placeholder="Basic usage" />
//     <span>用户备注</span>
// <InputNumber placeholder="Basic usage" />
// <span style={{display:"block"}}>用户角色</span>
// <SelectRole />

